package org.ishequ.weibo.adapater;

import java.util.List;
import org.ishequ.miduo.MiDuoActivity.ConfigHelper;
import org.ishequ.weibo.utils.ImageRel;
import org.ishequ.weibo.utils.gif.AsyncImageView;
import org.ishequ.widget.AutoGetMoreListView;
import org.ishequ.widget.OnGetMoreListener;
import org.ishequ.widget.OnRefreshListener;

import weibo4android.User;
import weibo4android.UserWapper;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.org.json.JSONException;
import weibo4android.org.json.JSONObject;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FriendsOrFollowsListAdapter extends BaseAdapter implements
								OnRefreshListener, OnGetMoreListener {
	
	static class ViewHolder {
		AsyncImageView asyncImageView;
		TextView info;
		Button btn;
	}
	
	private List<User> list;
	private List<JSONObject> list_relations;
	private UserWapper curUserWapper;
	private AutoGetMoreListView autoGetMoreListView;
	private Context context;
	private boolean flag; // true for follower, false for friends
	private String cid;
	private Weibo weibo;
	
	public FriendsOrFollowsListAdapter(Context context,List<User> list,AutoGetMoreListView autoGetMoreListView) {
		this.list = list;
		this.autoGetMoreListView = autoGetMoreListView;
		this.context = context;
		weibo = new Weibo();
		weibo.setToken(ConfigHelper.nowUser.getToken(), ConfigHelper.nowUser.getTokenSecret());
	}
	
	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public User getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final User user = list.get(position);
		final ViewHolder holder;
		if (convertView == null) {
			LinearLayout ll = new LinearLayout(context);
			ll.setOrientation(LinearLayout.HORIZONTAL);

			LinearLayout ll1 = new LinearLayout(context);
			ll1.setOrientation(LinearLayout.VERTICAL);
			ll1.setLayoutParams(new LayoutParams(130, LayoutParams.WRAP_CONTENT));
			AsyncImageView asyncImageView = new AsyncImageView(context);
			TextView info = new TextView(context);
			final Button btn = new Button(context);

			ll1.addView(asyncImageView);
			ll1.addView(btn);
			ll.addView(ll1);
			ll.addView(info);
			convertView = ll;

			holder = new ViewHolder();
			holder.asyncImageView = asyncImageView;
			holder.info = info;
			holder.btn = btn;
			convertView.setTag(holder);

		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		holder.asyncImageView.setPadding(10, 10, 10, 10);
		holder.asyncImageView.setProgressBitmaps(ImageRel
				.getBitmaps_avatar(context));
		holder.asyncImageView.setUrl(user.getProfileImageURL().toString());
		String info_text = "昵称: "
				+ user.getScreenName()
				+ "\n性别: "
				+ (user.getGender().equals("m") ? "男" : "女")
				+ "\n所在地: "
				+ user.getLocation()
				+ "\n博客地址："
				+ ((user.getURL() != null) ? user.getURL().toString() : "无")
				+ "\n粉丝数: " + user.getFollowersCount() + "\n关注数: "
				+ user.getFriendsCount();
		// Weibo weibo = OAuthConstant.getInstance().getWeibo();

		final String sex = (user.getGender().equals("m") ? "他" : "她");
		boolean following = false;
		boolean followed = true;
		try {
			// JSONObject object = weibo.showFriendships(OAuthConstant
			// .getInstance().getAccessToken().getUserId()
			// + "", user.getId() + "");
			JSONObject object = list_relations.get(position);
			JSONObject source = object.getJSONObject("source");
			JSONObject target = object.getJSONObject("target");
			following = Boolean.valueOf(target.getString("followed_by")); // 我是否关注他
			followed = Boolean.valueOf(source.getString("followed_by")); // 他是否关注我
			if (following && followed) {
				info_text = info_text + "\n" + "互相关注";
			} else {
				if (following) {
					info_text = info_text + "\n" + "我已关注" + sex;
				} else {
					info_text = info_text + "\n" + "我未关注" + sex;
				}
				if (followed) {
					info_text = info_text + "\n" + sex + "已关注我";
				} else {
					info_text = info_text + "\n" + sex + "未关注我";
				}
			}
		}
		// catch (WeiboException e) {
		// e.printStackTrace();
		// }
		catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {

		}

		holder.info.setPadding(10, 5, 10, 10);
		holder.info.setText(info_text);
		holder.info.setTextColor(Color.BLACK);

		if (following)
			holder.btn.setText("取消关注");
		else
			holder.btn.setText("关注" + sex);
		holder.btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (holder.btn.getText().equals("关注" + sex)) {
					try {
						// 官方要求要用post，函数createFriendship(id)是用get
						weibo.createFriendshipByUserid(user.getId() + "");
						holder.btn.setText("取消关注");
						Toast.makeText(context, "关注成功!",
								Toast.LENGTH_SHORT).show();
					} catch (WeiboException e) {
						e.printStackTrace();
						Toast.makeText(context, "关注失败!",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					try {
						weibo.destroyFriendship(user.getId() + "");
						holder.btn.setText("关注" + sex);
						Toast.makeText(context,
								"取消关注成功!", Toast.LENGTH_SHORT).show();
					} catch (WeiboException e) {
						e.printStackTrace();
						Toast.makeText(context,
								"取消关注失败!", Toast.LENGTH_SHORT).show();
					}
				}

			}
		});
		holder.btn.setFocusable(false);

		return convertView;
	}
	
	@Override
	public void onGetMore() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (curUserWapper.getNextCursor() != 0) {
					try {
						List<User> tmp;
						if (flag) {
							curUserWapper = weibo.getFollowersStatuses(cid,
												curUserWapper.getNextCursor());
							tmp = curUserWapper.getUsers();
						} else {
							curUserWapper = weibo.getFriendsStatuses(cid,
									             curUserWapper.getNextCursor());
							tmp = curUserWapper.getUsers();
						}
						list.addAll(tmp);
						getRelation(true, list.size() - tmp.size());
					} catch (WeiboException e) {
						e.printStackTrace();
					}
				}
				autoGetMoreListView.getMoreFinished();
			}
		}).start();
	}

	@Override
	public void onRefresh() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					List<User> tmp;
					if (flag)
						tmp = weibo.getFollowersStatuses(cid);
					else
						tmp = weibo.getFriendsStatuses(cid);
					list.clear();
					list = tmp;
					getRelation(false, 0);
				} catch (WeiboException e) {
					e.printStackTrace();
				}
				autoGetMoreListView.refreshFinished();
			}
		}).start();
	}
	
	protected void getRelation(boolean isGetMore, int beg) {
		if (!isGetMore)
			list_relations.clear();

		// boolean followed, following;
		for (int index = beg; index < list.size(); index++) {
			User user = list.get(index);
			// String text = "";
			try {
				// String sex = (user.getGender().equals("m") ? "他" : "她");
				list_relations.add(weibo.showFriendships(weibo.getUserId()
						+ "", user.getId() + ""));
				// JSONObject source = object.getJSONObject("source");
				// JSONObject target = object.getJSONObject("target");
				// following = Boolean.valueOf(target.getString("followed_by"));
				// // 我是否关注他
				// followed = Boolean.valueOf(source.getString("followed_by"));
				// // 他是否关注我
				// if (following && followed) {
				// text = text + "\n" + "互相关注";
				// } else {
				// if (following) {
				// text = text + "\n" + "我已关注" + sex;
				// } else {
				// text = text + "\n" + "我未关注" + sex;
				// }
				// if (followed) {
				// text = text + "\n" + sex + "已关注我";
				// } else {
				// text = text + "\n" + sex + "未关注我";
				// }
				// }
			} catch (WeiboException e) {
				e.printStackTrace();
				// } catch (JSONException e) {
				// e.printStackTrace();
			}
		}
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	public void setCid(String cid) {
		this.cid = cid;
	}

	public void setList_relations(List<JSONObject> listRelations) {
		list_relations = listRelations;
	}

	public void setCurUserWapper(UserWapper curUserWapper) {
		this.curUserWapper = curUserWapper;
	}

	public void setList(List<User> list) {
		this.list = list;
	}
	
}